<template>
  <div class="manage-view">
    <div class="header">
      <h1>店铺管理</h1>
      <div class="header-actions">
        <button class="add-shop-btn" @click="openAddShopModal">
          <i class="fas fa-plus"></i> 新增店铺
        </button>
        <button v-if="shopInfo.id" class="delete-shop-btn" @click="confirmDeleteShop">
          <i class="fas fa-trash-alt"></i> 删除店铺
        </button>
      </div>
      <div class="tabs">
        <div 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="{ active: activeTab === tab.id }"
          @click="activeTab = tab.id"
        >
          {{ tab.label }}
        </div>
      </div>
    </div>

    <div class="content">
      <!-- 店铺信息 -->
      <div v-if="activeTab === 'info'" class="info-section">
        <div class="section-header">
          <h2>店铺信息</h2>
          <button class="edit-btn" @click="handleEditToggle">
            {{ editMode.info ? '保存' : '编辑' }}
          </button>
        </div>
        
        <div class="info-grid">
          <div class="info-card">
            <h3>基本信息</h3>
            <div class="form-group">
              <label>店铺名称</label>
              <input type="text" v-model="shopInfo.name" :disabled="!editMode.info">
            </div>
            <div class="form-group">
              <label>联系电话</label>
              <input type="text" v-model="shopInfo.phone" :disabled="!editMode.info">
            </div>
            <div class="form-group">
              <label>营业时间</label>
              <div class="time-inputs">
                <input type="time" v-model="shopInfo.startTime" :disabled="!editMode.info">
                <span>至</span>
                <input type="time" v-model="shopInfo.endTime" :disabled="!editMode.info">
              </div>
            </div>
          </div>
          
          <div class="info-card">
            <h3>店铺地址</h3>
            <div class="form-group">
              <label>详细地址</label>
              <input type="text" v-model="shopInfo.address" :disabled="!editMode.info">
            </div>
            <div class="form-group">
              <label>配送费</label>
              <input type="number" v-model="shopInfo.deliveryFee" :disabled="!editMode.info">
            </div>
          </div>
          
          <div class="info-card">
            <h3>店铺图片</h3>
            <div class="image-upload">
              <div class="upload-area" @click="triggerUpload">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>点击上传店铺封面</p>
              </div>
              <input type="file" ref="fileInput" @change="handleFileUpload" hidden>
            </div>
            <div class="preview" v-if="shopInfo.image">
              <img :src="shopInfo.image" alt="店铺封面">
              <button class="remove-btn" @click="shopInfo.image = ''">删除</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 菜品管理 -->
      <div v-if="activeTab === 'menu'" class="menu-section">
        <div class="section-header">
          <h2>菜品管理</h2>
          <button class="add-btn" @click="openAddItemModal">
            <i class="fas fa-plus"></i> 添加菜品
          </button>
        </div>
        
        <div class="categories">
          <div 
            v-for="category in categories" 
            :key="category.id"
            :class="{ active: activeCategory === category.id }"
            @click="activeCategory = category.id"
          >
            {{ category.name }}
          </div>
          <button class="add-category" @click="openAddCategoryModal">
            <i class="fas fa-plus"></i> 添加分类
          </button>
        </div>
        
        <div class="menu-items">
          <div 
            v-for="item in filteredItems" 
            :key="item.id" 
            class="menu-item"
          >
            <div class="item-image" :style="{ backgroundImage: `url(${item.image})` }"></div>
            <div class="item-info">
              <h3>{{ item.name }}</h3>
              <p class="description">{{ item.description }}</p>
              <div class="price">¥{{ item.price }}</div>
              <div class="status">
                <span>状态:</span>
                <label class="switch">
                  <input type="checkbox" v-model="item.status" @change="updateItemStatus(item)">
                  <span class="slider round"></span>
                </label>
                <span>{{ item.status ? '在售' : '停售' }}</span>
              </div>
            </div>
            <div class="item-actions">
              <button class="edit-btn" @click="editItem(item)">
                <i class="fas fa-edit"></i>
              </button>
              <button class="delete-btn" @click="deleteItem(item.id)">
                <i class="fas fa-trash-alt"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加菜品模态框 -->
    <div v-if="showItemModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ editingItem ? '编辑菜品' : '添加菜品' }}</h3>
          <button class="close-btn" @click="closeItemModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>菜品名称</label>
            <input type="text" v-model="currentItem.name">
          </div>
          <div class="form-group">
            <label>菜品描述</label>
            <textarea v-model="currentItem.description"></textarea>
          </div>
          <div class="form-group">
            <label>价格 (¥)</label>
            <input type="number" v-model="currentItem.price">
          </div>
          <div class="form-group">
            <label>所属分类</label>
            <select v-model="currentItem.categoryId">
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>菜品图片</label>
            <div class="image-upload">
              <div class="upload-area" @click="triggerItemUpload">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>点击上传菜品图片</p>
              </div>
              <input type="file" ref="itemFileInput" @change="handleItemFileUpload" hidden>
            </div>
            <div class="preview" v-if="currentItem.image">
              <img :src="currentItem.image" alt="菜品图片">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeItemModal">取消</button>
          <button class="save-btn" @click="saveItem">{{ editingItem ? '保存' : '添加' }}</button>
        </div>
      </div>
    </div>

    <!-- 添加分类模态框 -->
    <div v-if="showCategoryModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加分类</h3>
          <button class="close-btn" @click="closeCategoryModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>分类名称</label>
            <input type="text" v-model="newCategoryName">
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeCategoryModal">取消</button>
          <button class="save-btn" @click="addCategory">添加</button>
        </div>
      </div>
    </div>

    <!-- 新增店铺模态框 -->
    <div v-if="showAddShopModal" class="modal">
      <div class="modal-content large-modal">
        <div class="modal-header">
          <h3>新增店铺</h3>
          <button class="close-btn" @click="closeAddShopModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-group">
              <label>店铺名称 *</label>
              <input type="text" v-model="newShopData.name" placeholder="请输入店铺名称">
            </div>
            <div class="form-group">
              <label>联系电话</label>
              <input type="text" v-model="newShopData.phone" placeholder="请输入联系电话">
            </div>
            <div class="form-group">
              <label>店铺地址</label>
              <input type="text" v-model="newShopData.address" placeholder="请输入店铺地址">
            </div>
            <div class="form-group">
              <label>配送费 (元)</label>
              <input type="number" v-model="newShopData.deliveryFee" placeholder="请输入配送费" min="0" step="0.1">
            </div>
            <div class="form-group">
              <label>最低起送金额 (元)</label>
              <input type="number" v-model="newShopData.minOrderAmount" placeholder="请输入最低起送金额" min="0" step="0.1">
            </div>
            <div class="form-group full-width">
              <label>店铺描述</label>
              <textarea v-model="newShopData.description" placeholder="请输入店铺描述" rows="3"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddShopModal">取消</button>
          <button class="save-btn" @click="createShop" :disabled="!newShopData.name">创建店铺</button>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteConfirm" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="showDeleteConfirm = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="delete-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <p>您确定要删除店铺 <strong>"{{ shopInfo.name }}"</strong> 吗？</p>
            <p class="warning-text">此操作不可撤销，将同时删除店铺下的所有商品和分类！</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showDeleteConfirm = false">取消</button>
          <button class="delete-btn" @click="deleteShop">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { selectEq, update, insertShop, deleteById, type Shop } from '@/http/Shop';
import { selectById } from '@/http/User';
import { 
  selectEq as getGoods, 
  insert as insertGoods, 
  update as updateGoods, 
  deleteById as deleteGoods,
  type Goods 
} from '@/http/Goods';
import { 
  selectEq as getGoodsCategories, 
  insert as insertGoodsCategory, 
  type GoodsCategory 
} from '@/http/GoodsCategory';
import { ref, computed, reactive, onMounted } from 'vue';
import { useUserIdStore } from '@/stores/UserId';
import { message } from '@/utils/message';

interface Tab {
  id: string;
  label: string;
}

const userIdStore = useUserIdStore();
const loading = ref(true);

const shopInfo = ref<Shop>({
  id: null,
  createTime: null,
  updateTime: null,
  relaUserId: null,
  name: null,
  description: null,
  logoAddress: null,
  address: null,
  positionX: null,
  positionY: null,
  phone: null,
  startTime: null,
  endTime: null,
  minOrderAmount: null,
  deliveryFee: null,
  avRating: null,
  avAmount: null,
  monthlyOrderCount: null,
  image: null
});

// 加载店铺信息
const loadShopInfo = async () => {
  try {
    console.log('🚀 开始加载店铺信息...');
    
    // 首先尝试从本地存储恢复用户状态
    if (!userIdStore.currentUserId) {
      console.log('⚠️ 用户ID为空，尝试从本地存储恢复...');
      userIdStore.restoreFromStorage();
      
      // 恢复后再次检查
      if (!userIdStore.currentUserId) {
        message.warning('请先登录');
        console.log('❌ 恢复失败，用户未登录');
        return;
      } else {
        console.log('✅ 用户状态已从本地存储恢复:', userIdStore.currentUserId);
        message.success('欢迎回来！');
      }
    }

    const query: Record<string, any> = {};
    if (userIdStore.currentUserId) query.rela_user_id = userIdStore.currentUserId;
    const response = await selectEq(query);
    
    if (response.data && response.data.length > 0) {
      shopInfo.value = response.data[0];
      console.log('✅ 店铺信息加载成功:', shopInfo.value);
      
      // 加载商品和分类数据
      await loadMenuData();
    } else {
      console.log('⚠️ 没有找到店铺信息');
      message.info('您还没有店铺，请先创建店铺');
    }
  } catch (error: any) {
    console.error('❌ 加载店铺信息失败:', error);
    
    // 如果是认证相关错误，提示重新登录
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      message.error('登录已过期，请重新登录');
      userIdStore.logout();
    } else {
      message.error('加载店铺信息失败: ' + (error.message || '网络错误'));
    }
  }
};

const tabs = ref<Tab[]>([
  { id: 'info', label: '店铺信息' },
  { id: 'menu', label: '菜品管理' },
]);

const activeTab = ref('info');

interface EditMode {
  info: boolean;
}

const editMode = reactive<EditMode>({
  info: false
});

// 使用后端数据类型
interface DisplayCategory {
  id: number;
  name: string;
  shopId?: number;
}

interface DisplayMenuItem {
  id: number;
  name: string;
  description: string;
  price: number;
  image: string;
  categoryId: number;
  status: boolean;
  shopId?: number;
}

const categories = ref<DisplayCategory[]>([]);
const menuItems = ref<DisplayMenuItem[]>([]);

const activeCategory = ref(1);

// 加载菜单数据
const loadMenuData = async () => {
  if (!shopInfo.value.id) return;
  
  try {
    console.log('🚀 开始加载菜单数据...');
    
    // 加载商品分类
    const categoriesResponse = await getGoodsCategories({ rela_shop_id: shopInfo.value.id });
    
    if (categoriesResponse.data && categoriesResponse.data.length > 0) {
      const convertedCategories = categoriesResponse.data.map(cat => ({
        id: cat.id || 0,
        name: cat.name || '未命名分类',
        shopId: cat.relaShopId || undefined
      }));
      categories.value = convertedCategories;
      
      // 设置默认选中第一个分类
      if (convertedCategories.length > 0) {
        activeCategory.value = convertedCategories[0].id;
      }
      
      console.log('✅ 分类数据加载成功:', convertedCategories.length, '个分类');
    } else {
      console.log('⚠️ 没有分类数据');
      categories.value = [];
    }
    
    // 加载商品
    const goodsResponse = await getGoods({ rela_shop_id: shopInfo.value.id });
    
    if (goodsResponse.data && goodsResponse.data.length > 0) {
      const convertedGoods = goodsResponse.data.map(goods => ({
        id: goods.id || 0,
        name: goods.name || '未命名商品',
        description: goods.description || '',
        price: (goods.price || 0) / 100, // 转换为元
        image: goods.imageAddress || '/default-food.jpg',
        categoryId: goods.relaGoodsCategoryId || 0,
        status: goods.isOn || false,
        shopId: goods.relaShopId || undefined
      }));
      menuItems.value = convertedGoods;
      
      console.log('✅ 商品数据加载成功:', convertedGoods.length, '个商品');
    } else {
      console.log('⚠️ 没有商品数据');
      menuItems.value = [];
    }
  } catch (error: any) {
    console.error('❌ 加载菜单数据失败:', error);
    message.error('加载菜单数据失败: ' + (error.message || '网络错误'));
    
    // 错误时可以使用静态数据作为备用
    // categories.value = staticCategories.value;
    // menuItems.value = staticMenuItems.value;
  }
};

const filteredItems = computed(() => {
  return menuItems.value.filter(item => item.categoryId === activeCategory.value);
});

// 修改按钮点击事件，分离编辑和保存逻辑
function handleEditToggle() {
  if (!editMode.info) {
    // 进入编辑模式
    editMode.info = true;
    console.log('🖊️ 进入编辑模式');
  } else {
    // 保存模式 - 调用更新函数
    saveShopInfo();
  }
}

// 保存店铺信息的独立函数
const saveShopInfo = async () => {
  try {
    console.log('💾 保存店铺信息...');
    
    // 数据验证
    if (!shopInfo.value.id) {
      message.error('店铺ID不能为空');
      return;
    }
    
    // 准备更新数据，转换字段名和数据格式
    const updateData: Partial<Shop> = {
      id: shopInfo.value.id,
      relaUserId: shopInfo.value.relaUserId,
      name: shopInfo.value.name,
      description: shopInfo.value.description,
      logoAddress: shopInfo.value.logoAddress,
      address: shopInfo.value.address,
      positionX: shopInfo.value.positionX,
      positionY: shopInfo.value.positionY,
      phone: shopInfo.value.phone,
      // 时间格式转换 - 注释掉有问题的时间字段
      // startTime: shopInfo.value.startTime,
      // endTime: shopInfo.value.endTime,
      minOrderAmount: shopInfo.value.minOrderAmount,
      deliveryFee: shopInfo.value.deliveryFee,
      avRating: shopInfo.value.avRating,
      avAmount: shopInfo.value.avAmount,
      monthlyOrderCount: shopInfo.value.monthlyOrderCount,
      image: shopInfo.value.image
    };
    
    console.log('📤 发送更新数据:', updateData);
    
    const response = await update(shopInfo.value.id, updateData as Shop);
    
    // 更新成功后同步本地数据
    if (response.data) {
      shopInfo.value = response.data;
      editMode.info = false; // 退出编辑模式
      message.success('店铺信息保存成功');
      console.log('✅ 店铺信息保存成功:', response.data);
    } else {
      throw new Error('服务器返回数据为空');
    }
    
  } catch (error: any) {
    console.error('❌ 保存店铺信息失败:', error);
    
    // 详细错误处理
    let errorMessage = '保存店铺信息失败';
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status;
      const data = error.response.data;
      
      if (status === 400) {
        errorMessage = '请求参数错误: ' + (data?.message || '数据格式不正确');
      } else if (status === 404) {
        errorMessage = '店铺不存在';
      } else if (status === 500) {
        errorMessage = '服务器内部错误';
      } else {
        errorMessage = `服务器错误 (${status}): ${data?.message || '未知错误'}`;
      }
    } else if (error.request) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置';
    } else {
      // 其他错误
      errorMessage = error.message || '未知错误';
    }
    
    message.error(errorMessage);
    
    // 发生错误时保持编辑模式，让用户可以重试
    // editMode.info 保持 true 状态
  }
};

// 模态框相关状态
const showItemModal = ref(false);
const showCategoryModal = ref(false);
const editingItem = ref<DisplayMenuItem | null>(null);
const currentItem = reactive<DisplayMenuItem>({
  id: 0,
  name: '',
  description: '',
  price: 0,
  image: '',
  categoryId: 1,
  status: true
});
const newCategoryName = ref('');

// 文件上传
const fileInput = ref<HTMLInputElement | null>(null);
const itemFileInput = ref<HTMLInputElement | null>(null);

function triggerUpload() {
  if (fileInput.value) {
    fileInput.value.click();
  }
}

function handleFileUpload(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target && e.target.result) {
        shopInfo.value.image = e.target.result as string;
      }
    };
    reader.readAsDataURL(file);
  }
}

function triggerItemUpload() {
  if (itemFileInput.value) {
    itemFileInput.value.click();
  }
}

function handleItemFileUpload(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target && e.target.result) {
        currentItem.image = e.target.result as string;
      }
    };
    reader.readAsDataURL(file);
  }
}

// 菜品操作
function openAddItemModal() {
  editingItem.value = null;
  currentItem.id = 0;
  currentItem.name = '';
  currentItem.description = '';
  currentItem.price = 0;
  currentItem.image = '';
  currentItem.categoryId = activeCategory.value;
  currentItem.status = true;
  showItemModal.value = true;
}

function editItem(item: DisplayMenuItem) {
  editingItem.value = item;
  currentItem.id = item.id;
  currentItem.name = item.name;
  currentItem.description = item.description;
  currentItem.price = item.price;
  currentItem.image = item.image;
  currentItem.categoryId = item.categoryId;
  currentItem.status = item.status;
  showItemModal.value = true;
}

async function saveItem() {
  if (!shopInfo.value.id) {
    message.error('店铺信息不完整');
    return;
  }
  
  try {
    console.log('💾 保存商品:', currentItem);
    
    // 准备后端数据格式
    const goodsData: Partial<Goods> = {
      relaShopId: shopInfo.value.id,
      relaGoodsCategoryId: currentItem.categoryId,
      name: currentItem.name,
      description: currentItem.description,
      price: Math.round(currentItem.price * 100), // 转换为分
      imageAddress: currentItem.image,
      isOn: currentItem.status,
      monthlySaleCount: 0,
      tag: '',
      innerIndex: 0
    };
    
  if (editingItem.value) {
      // 更新现有商品
      goodsData.id = currentItem.id;
      const response = await updateGoods(currentItem.id, goodsData as Goods);
      
    const index = menuItems.value.findIndex(item => item.id === editingItem.value!.id);
    if (index !== -1) {
      menuItems.value[index] = { ...currentItem };
    }
      
      message.success('商品更新成功');
      console.log('✅ 商品更新成功:', response.data);
  } else {
      // 添加新商品
      const response = await insertGoods(goodsData as Goods);
      
      const newItem = {
      ...currentItem,
        id: response.data.id || Date.now() // 使用返回的ID或时间戳
      };
      menuItems.value.push(newItem);
      
      message.success('商品添加成功');
      console.log('✅ 商品添加成功:', response.data);
  }
    
  closeItemModal();
  } catch (error: any) {
    console.error('❌ 保存商品失败:', error);
    message.error('保存商品失败: ' + (error.message || '网络错误'));
  }
}

async function deleteItem(id: number) {
  if (!confirm('确定要删除这个菜品吗？')) return;
  
  try {
    console.log('🗑️ 删除商品:', id);
    
    await deleteGoods(id);
    menuItems.value = menuItems.value.filter(item => item.id !== id);
    
    message.success('商品删除成功');
    console.log('✅ 商品删除成功');
  } catch (error: any) {
    console.error('❌ 删除商品失败:', error);
    message.error('删除商品失败: ' + (error.message || '网络错误'));
  }
}

function closeItemModal() {
  showItemModal.value = false;
}

// 分类操作
function openAddCategoryModal() {
  newCategoryName.value = '';
  showCategoryModal.value = true;
}

async function addCategory() {
  if (!newCategoryName.value.trim()) {
    message.warning('请输入分类名称');
    return;
  }
  
  if (!shopInfo.value.id) {
    message.error('店铺信息不完整');
    return;
  }
  
  try {
    console.log('➕ 添加分类:', newCategoryName.value);
    
    const categoryData: Partial<GoodsCategory> = {
      relaShopId: shopInfo.value.id,
      name: newCategoryName.value,
      innerIndex: categories.value.length
    };
    
    const response = await insertGoodsCategory(categoryData as GoodsCategory);
    
    const newCategory = {
      id: response.data.id || Date.now(),
      name: newCategoryName.value,
      shopId: shopInfo.value.id
    };
    
    categories.value.push(newCategory);
    
    message.success('分类添加成功');
    console.log('✅ 分类添加成功:', response.data);
    
    closeCategoryModal();
  } catch (error: any) {
    console.error('❌ 添加分类失败:', error);
    message.error('添加分类失败: ' + (error.message || '网络错误'));
  }
}

function closeCategoryModal() {
  showCategoryModal.value = false;
}

// 页面加载时获取数据
onMounted(() => {
  loadShopInfo();
});

// 更新商品状态的函数
async function updateItemStatus(item: DisplayMenuItem) {
  if (!shopInfo.value.id) {
    message.error('店铺信息不完整');
    return;
  }
  
  try {
    console.log('🔄 更新商品状态:', item.name, '状态:', item.status ? '在售' : '停售');
    
    // 准备后端数据格式
    const goodsData: Partial<Goods> = {
      id: item.id,
      relaShopId: shopInfo.value.id,
      relaGoodsCategoryId: item.categoryId,
      name: item.name,
      description: item.description,
      price: Math.round(item.price * 100), // 转换为分
      imageAddress: item.image,
      isOn: item.status, // 更新状态
      monthlySaleCount: 0,
      tag: '',
      innerIndex: 0
    };
    
    const response = await updateGoods(item.id, goodsData as Goods);
    
    // 显示成功消息
    message.success(`商品${item.status ? '上架' : '下架'}成功`);
    console.log('✅ 商品状态更新成功:', response.data);
    
  } catch (error: any) {
    console.error('❌ 更新商品状态失败:', error);
    
    // 回滚状态变化
    item.status = !item.status;
    
    // 显示错误消息
    let errorMessage = '更新商品状态失败';
    if (error.response) {
      const status = error.response.status;
      const data = error.response.data;
      
      if (status === 400) {
        errorMessage = '请求参数错误: ' + (data?.message || '数据格式不正确');
      } else if (status === 404) {
        errorMessage = '商品不存在';
      } else if (status === 500) {
        errorMessage = '服务器内部错误';
      } else {
        errorMessage = `服务器错误 (${status}): ${data?.message || '未知错误'}`;
      }
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置';
    } else {
      errorMessage = error.message || '未知错误';
    }
    
    message.error(errorMessage);
  }
}

// 新增店铺相关状态
const showAddShopModal = ref(false);
const newShopData = reactive<Partial<Shop>>({
  name: '',
  description: '',
  address: '',
  phone: '',
  deliveryFee: 0,
  minOrderAmount: 0
});

function openAddShopModal() {
  // 重置表单数据
  Object.assign(newShopData, {
    name: '',
    description: '',
    address: '',
    phone: '',
    deliveryFee: 0,
    minOrderAmount: 0
  });
  showAddShopModal.value = true;
}

function closeAddShopModal() {
  showAddShopModal.value = false;
}

async function createShop() {
  if (!newShopData.name || !newShopData.name.trim()) {
    message.warning('请输入店铺名称');
    return;
  }
  
  if (!newShopData.address || !newShopData.address.trim()) {
    message.warning('请输入店铺地址');
    return;
  }
  
  if (!newShopData.deliveryFee || newShopData.deliveryFee < 0) {
    message.warning('请输入有效的配送费');
    return;
  }
  
  if (!newShopData.minOrderAmount || newShopData.minOrderAmount < 0) {
    message.warning('请输入有效的最低起送金额');
    return;
  }
  
  try {
    console.log('💾 创建店铺:', newShopData);
    
    // 准备店铺数据
    const shopData: Partial<Shop> = {
      relaUserId: userIdStore.currentUserId,
      name: newShopData.name,
      description: newShopData.description,
      address: newShopData.address,
      phone: newShopData.phone,
      deliveryFee: Math.round((newShopData.deliveryFee || 0) * 100), // 转换为分
      minOrderAmount: Math.round((newShopData.minOrderAmount || 0) * 100), // 转换为分
      avRating: 5.0,
      avAmount: 0,
      monthlyOrderCount: 0
    };
    
    const response = await insertShop(shopData as Shop);
    
    if (response.data) {
      shopInfo.value = response.data;
      message.success('店铺创建成功');
      console.log('✅ 店铺创建成功:', response.data);
      closeAddShopModal();
      // 重新加载店铺信息
      await loadShopInfo();
    } else {
      throw new Error('服务器返回数据为空');
    }
  } catch (error: any) {
    console.error('❌ 创建店铺失败:', error);
    message.error('创建店铺失败: ' + (error.message || '网络错误'));
  }
}

// 删除店铺相关状态
const showDeleteConfirm = ref(false);

function confirmDeleteShop() {
  showDeleteConfirm.value = true;
}

async function deleteShop() {
  if (!shopInfo.value.id) {
    message.error('店铺信息不完整');
    return;
  }
  
  try {
    console.log('🗑️ 删除店铺:', shopInfo.value.id);
    
    await deleteById(shopInfo.value.id);
    
    // 重置店铺信息
    shopInfo.value = {
      id: null,
      createTime: null,
      updateTime: null,
      relaUserId: null,
      name: null,
      description: null,
      logoAddress: null,
      address: null,
      positionX: null,
      positionY: null,
      phone: null,
      startTime: null,
      endTime: null,
      minOrderAmount: null,
      deliveryFee: null,
      avRating: null,
      avAmount: null,
      monthlyOrderCount: null,
      image: null
    };
    
    // 清空相关数据
    menuItems.value = [];
    categories.value = [];
    activeCategory.value = 1;
    
    message.success('店铺删除成功');
    console.log('✅ 店铺删除成功');
    showDeleteConfirm.value = false;
  } catch (error: any) {
    console.error('❌ 删除店铺失败:', error);
    message.error('删除店铺失败: ' + (error.message || '网络错误'));
  }
}
</script>

<style scoped>
.manage-view {
  width: 100%;
  height: 100vh;
  padding: 30px;
  background: #f8fafc;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  overflow-y: auto;
  box-sizing: border-box;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  color: #2d3748;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.add-shop-btn, .delete-shop-btn {
  padding: 8px 20px;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.add-shop-btn {
  background: #4299e1;
}

.add-shop-btn:hover {
  background: #3182ce;
}

.delete-shop-btn {
  background: #e53e3e;
}

.delete-shop-btn:hover {
  background: #c53030;
}

.tabs {
  display: flex;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.tabs div {
  padding: 15px 30px;
  cursor: pointer;
  font-weight: 600;
  color: #718096;
  transition: all 0.3s;
  border-bottom: 3px solid transparent;
}

.tabs div:hover {
  color: #4299e1;
}

.tabs div.active {
  color: #4299e1;
  border-bottom: 3px solid #4299e1;
  background: #f0f7ff;
}

.content {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.section-header h2 {
  margin: 0;
  color: #2d3748;
  font-size: 20px;
}

.edit-btn, .add-btn {
  padding: 8px 20px;
  background: #4299e1;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.edit-btn:hover, .add-btn:hover {
  background: #3182ce;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
}

.info-card h3 {
  margin: 0 0 20px;
  color: #2d3748;
  font-size: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #4a5568;
  font-size: 14px;
  font-weight: 500;
}

.form-group input, .form-group select, .form-group textarea {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  color: #4a5568;
  font-size: 14px;
}

.form-group input:disabled, .form-group select:disabled {
  background: #f1f5f9;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.time-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.time-inputs span {
  color: #718096;
}

.image-upload {
  margin-bottom: 15px;
}

.upload-area {
  border: 2px dashed #cbd5e0;
  border-radius: 8px;
  padding: 30px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #4299e1;
  background: #f0f7ff;
}

.upload-area i {
  font-size: 40px;
  color: #a0aec0;
  margin-bottom: 10px;
}

.upload-area p {
  margin: 0;
  color: #718096;
}

.preview {
  margin-top: 15px;
  position: relative;
}

.preview img {
  width: 100%;
  border-radius: 8px;
  max-height: 200px;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
}

.categories {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.categories div {
  padding: 8px 20px;
  background: #f1f5f9;
  border-radius: 20px;
  cursor: pointer;
  color: #4a5568;
  transition: all 0.3s;
}

.categories div:hover {
  background: #e2e8f0;
}

.categories div.active {
  background: #4299e1;
  color: white;
}

.add-category {
  background: none;
  border: 1px dashed #cbd5e0;
  border-radius: 20px;
  padding: 8px 20px;
  color: #718096;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.add-category:hover {
  border-color: #4299e1;
  color: #4299e1;
}

.menu-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.menu-item {
  display: flex;
  background: #f8fafc;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s;
  border: 1px solid #e2e8f0;
}

.menu-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.item-image {
  width: 100px;
  height: 100px;
  background-size: cover;
  background-position: center;
}

.item-info {
  flex: 1;
  padding: 15px;
}

.item-info h3 {
  margin: 0 0 8px;
  color: #2d3748;
  font-size: 16px;
}

.description {
  margin: 0 0 10px;
  color: #718096;
  font-size: 13px;
  line-height: 1.4;
}

.price {
  font-weight: bold;
  font-size: 18px;
  color: #e53e3e;
  margin-bottom: 10px;
}

.status {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #718096;
  font-size: 13px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #cbd5e0;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
}

input:checked + .slider {
  background-color: #48bb78;
}

input:checked + .slider:before {
  transform: translateX(20px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.item-actions {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background: #edf2f7;
}

.edit-btn, .delete-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  cursor: pointer;
  margin: 5px 0;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-btn {
  background: #4299e1;
  color: white;
}

.edit-btn:hover {
  background: #3182ce;
}

.delete-btn {
  background: #fc8181;
  color: white;
}

.delete-btn:hover {
  background: #e53e3e;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 500px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  margin: 0;
  color: #2d3748;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #718096;
  cursor: pointer;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #f1f5f9;
  color: #e53e3e;
}

.modal-body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
  gap: 10px;
}

.cancel-btn, .save-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: #f1f5f9;
  color: #4a5568;
  border: 1px solid #e2e8f0;
}

.cancel-btn:hover {
  background: #e2e8f0;
}

.save-btn {
  background: #4299e1;
  color: white;
  border: none;
}

.save-btn:hover {
  background: #3182ce;
}

.large-modal {
  max-width: 800px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.full-width {
  grid-column: span 2;
}

.delete-warning {
  text-align: center;
  padding: 20px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #f8fafc;
}

.delete-warning i {
  font-size: 40px;
  color: #e53e3e;
  margin-bottom: 10px;
}

.delete-warning p {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.warning-text {
  margin-top: 10px;
  color: #718096;
  font-size: 14px;
}
</style>